import React, { useReducer, useEffect, useState, useRef } from "react";
// import { post } from '../../server/api'
import JSONEditor from "jsoneditor";
import "jsoneditor/dist/jsoneditor.css";

const userState = {
  name: "mike",
  team: "大师组",
  address: "光明大道",
  age: 11,
};

const personalReducer = (prevState: any, action: any) => {
  switch (action.type) {
    case "updateName":
      return {
        ...prevState,
        name: action.name,
      };
    case "updateTeam":
      return {
        ...prevState,
        team: action.team,
      };
    case "updateAddress":
      return {
        ...prevState,
        address: action.address,
      };
  }
};

const Test = () => {
  const [state, dispatch] = useReducer(personalReducer, userState);
  const [count, setCount] = useState(0);
  const lastCount = useRef(count);

  useEffect(() => {
    lastCount.current = count;
    setTimeout(() => {
      console.log(`You clicked ${lastCount.current} times`);
    }, 3000);
  });

  let container: any = null;
  let editor: any = null;

  useEffect(() => {
    container = document.getElementById("jsoneditor");
    if (container) {
      editor = new JSONEditor(container, {
        onChange: () => {
          console.log("==editor.get()====", editor.get());
        },
      });
      var json = {
        Array: [1, 2, 3],
        Boolean: true,
        Null: null,
        Number: 123,
        Object: { a: "b", c: "d" },
        String: "Hello World",
      };
      editor.set(json);
    }
    console.log("===container====", container);
  }, []);

  return (
    <div>
      <h1>1.useReduce的使用：</h1>
      <p>name: {state.name}</p>
      <button
        onClick={() =>
          dispatch({
            type: "updateName",
            name: "11111",
          })
        }
      >
        点击
      </button>

      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        +
      </button>

      <div id="jsoneditor" style={{ width: 400, height: 400 }}></div>
    </div>
  );
};

export default Test;
